package ads.pin.pinmon.dal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class EntityManager {

	public void executeQuery(String sql, Object... params) {
		PreparedStatement pstm = null;
		Connection conn = null;

		try {
			conn = ConnectionFactory.getConnection();

			pstm = conn.prepareStatement(sql);

			for (int i = 1; i <= params.length; i++) {
				pstm.setObject(i, params[i - 1]);
			}

			pstm.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstm != null && !pstm.isClosed()) {
					pstm.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (conn != null && !conn.isClosed()) {
						conn.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public Object getSingleResult(String sql, Object... params) {
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet resultSet = null;

		try {
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);

			for (int i = 1; i <= params.length; i++) {
				pstm.setObject(i, params[i - 1]);
			}

			resultSet = pstm.executeQuery();

			if (resultSet.next()) {
				return this.treatResultSet(resultSet);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null && !resultSet.isClosed()) {
					resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (pstm != null && !pstm.isClosed()) {
						pstm.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					try {
						if (conn != null && !conn.isClosed()) {
							conn.close();
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}

		return null;
	}

	public abstract Object treatResultSet(ResultSet resultSet)
			throws SQLException;

}
